package net.qiqbframework.lifecycle;

import javax.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;

/**
 * 生命周期处理器注册事件
 */
public interface LifecycleHandlerRegister {
    /**
     * 生命周期组件开始时，将执行注册的处理实现
     *
     * @param phase 执行此操作的阶段
     * @param handler  要执行的操作
     */
    void onStart(int phase, @Nonnull LifecycleHandler handler);

    /**
     * 生命周期组件关闭时，将执行注册的实现
     *
     * @param phase 执行此操作的阶段
     * @param handler 要执行的操作
     */
    void onShutdown(int phase, @Nonnull LifecycleHandler handler);

    default void onStart(int phase, @Nonnull Runnable action) {
        onStart(phase, () -> {
            try {
                action.run();
                return CompletableFuture.completedFuture(null);
            } catch (Exception e) {
                CompletableFuture<Void> cf = new CompletableFuture<>();
                cf.completeExceptionally(e);
                return cf;
            }
        });
    }

    default void onShutdown(int phase, @Nonnull Runnable action) {
        onShutdown(phase, () -> {
            try {
                action.run();
                return CompletableFuture.completedFuture(null);
            } catch (Exception e) {
                CompletableFuture<Void> cf = new CompletableFuture<>();
                cf.completeExceptionally(e);
                return cf;
            }
        });
    }

}
